<template>
  <div>
    <div class="page-gird-container">
      <div class="bg-color-body-gray">
        <div>
          <span class="color-lighten-dark-gray">账户余额（元）</span>
          <span class="color-dark-black">{{ balance }}</span>
        </div>
        <Button>充值记录</Button>
      </div>
      <Tabs v-model="tabValue" :value="tabValue" type="card" :animated="false">
        <!-- 在线充值 -->
        <TabPane label="在线充值" name="online">
          <Form
            ref="ruleValidate"
            :rules="ruleValidate"
            :model="payForm" 
          >
            <FormItem label="充值金额：" prop="money" label-width="120">
              <Input
                v-model="payForm.money"
                placeholder="充值金额不能为0"
                style="width: 200px"
              />
            </FormItem>
            <FormItem label="支付方式：" prop="payMethod" label-width="120">
              <ul class="r-pay">
                <li class="r-pay-list" @click="changePayMethod(1)">
                  <i class="icon-alipay"></i>
                  <i
                    class="payment-select"
                    :style="{
                      display: activePayMethod == 1 ? 'block' : 'none',
                    }"
                  ></i>
                </li>
                <li class="r-pay-list" @click="changePayMethod(2)">
                  <i class="icon-alipay1"></i>
                  <i
                    class="payment-select"
                    :style="{
                      display: activePayMethod == 2 ? 'block' : 'none',
                    }"
                  ></i>
                </li>
              </ul>
              <Button type="primary" @click="recharge('ruleValidate')"
                >立即充值</Button
              >
            </FormItem>
          </Form>
        </TabPane>
        <!-- 线下汇款 -->
        <!-- <TabPane label="线下汇款" name="inline">
          <Timeline>
            <TimelineItem>
              <p class="time">
                请您通过网银转账，或者自行到银行进行汇款，汇款账号如下：
              </p>
              <Table
                :stripe="true"
                :columns="columns"
                :data="data"
              ></Table>
            </TimelineItem>
            <TimelineItem>
              <p class="time">
                请您通过网银转账，或者自行到银行进行汇款，汇款账号如下：
              </p>
              <Button type="primary" @click="modal = true"
                >提交汇款凭据审核</Button
              >
            </TimelineItem>
            <TimelineItem>
              <p class="time">
                提交汇款信息成功后，等待工作财务审核后汇款金额充值到账。
              </p>
              <p style="color: #a3a3a3">
                我们将通过短信、邮件、站内信的方式向您反馈充值结果，也可前往<span
                  style="color: #08f"
                  >线下汇款记录</span
                >页面查看汇款进度。
              </p>
            </TimelineItem>
          </Timeline>
        </TabPane> -->
      </Tabs>
    </div>
    <Modal v-model="modal" title="提交汇款凭证" :footer-hide="true">
      <Form
        ref="formValidate"
        :model="formValidate"
        label-width="121"
        :rules="payRule"
        label-position="right"
      >
        <FormItem label="转账金额：" prop="money">
          <Input v-model="formValidate.money"></Input>
        </FormItem>
        <FormItem label="汇款银行户名：" prop="bankUsername">
          <Input v-model="formValidate.bankUsername"></Input>
        </FormItem>
        <FormItem label="汇款开户银行：" prop="bankName">
          <Input v-model="formValidate.bankName"></Input>
        </FormItem>
        <FormItem label="汇款银行账号：" prop="bankAccount">
          <Input v-model="formValidate.bankAccount"></Input>
        </FormItem>
        <FormItem label="上传转账凭证：" prop="remittanceVoucher">
          <Upload
            :format="['jpg', 'jpeg', 'png']"
            :action="action"
            name="image"
            :data="fileData"
            :headers="headers"
            :on-success="uploadSuc"
          >
            <Button icon="ios-cloud-upload-outline">点击上传</Button>
          </Upload>
        </FormItem>
        <Button type="primary" style="margin-right: 10px; margin-left: 121px;" @click="handleSubmit">确认提交</Button>
        <Button @click="modal = false">取消</Button>
      </Form>
    </Modal>
  </div>
  <Modal v-model="wechatpayModal" :footer-hide="true" @on-visible-change="visibleChange">
    <div style="display: flex; flex-direction: column; align-items: center;">
      <p>请使用“微信扫一扫”扫描下方二维码进行在线充值</p>
      <img :src="wechatpayPCImg" alt="" />
      <canvas id="canvas"></canvas>
    </div>
  </Modal>
</template>

<script>
    import {
        rechargeAlipayPC,
        wechatpayPC,
        financialRemittanceVoucher,
        resultsQuery
    } from "@/api/finance";
    import { setInfo } from '@/libs/userInfo'
    import { memberInfo } from "@/api/set";
    import cookies from "@/libs/util.cookies";
    import QRCode from "qrcode";

    export default {
        name: 'finance-moneyManage-recharge',
        data() {
            return {
                alipayModal: false,
                wechatpayModal: false,
                html: "",
                modal: false,
                alipay: false,
                activePayMethod: 1,
                wechatpayPCImg: "",
                payForm: {
                    money: "",
                },
                action: '',
                tabValue: 'online',
                headers: {},
                fileData: {
                    source: "Remittances",
                },
                ruleValidate: {
                    money: [
                        {
                            required: true,
                            message: "请输入充值金额",
                            trigger: "blur",
                        },
                    ],
                },
                columns: [
                    {
                        title: "开户名称",
                        key: "name",
                    },
                    {
                        title: "开户银行",
                        key: "address",
                    },
                    {
                        title: "银行账号",
                        key: "username",
                    },
                    {
                        title: "汇款备注",
                        key: "remark",
                    },
                ],
                data: [
                    {
                        name: "深圳前海小鸟云计算有限公司",
                        address: "中国银行深圳科技园支行",
                        username: "773166046065",
                        remark: "合作商ID 14489",
                    },
                ],
                formValidate: {
                    money: "",
                    bankUsername: "",
                    bankName: "",
                    bankAccount: "",
                    remittanceVoucher: "",
                },
                payRule: {
                    money: [
                        {
                            required: true,
                            message: "请输入转账金额",
                            trigger: "blur",
                        },
                    ],
                    bankUsername: [
                        {
                            required: true,
                            message: "请输入汇款银行户名",
                            trigger: "blur",
                        },
                    ],
                    bankName: [
                        {
                            required: true,
                            message: "请输入汇款开户银行",
                            trigger: "blur",
                        },
                    ],
                    bankAccount: [
                        {
                            required: true,
                            message: "请输入汇款银行账号",
                            trigger: "blur",
                        },
                    ],
                    remittanceVoucher: [
                        {
                            required: true,
                            message: "请上传转账凭证",
                            trigger: "blur",
                        },
                    ],
                },
                balance: '',
                timer: null
            };
        },
        methods: {
            /**
             * @description 切换支付方式
             * 1：支付宝支付  2：微信支付
             */
            changePayMethod(val) {
                this.activePayMethod = val;
            },
            /**
             * @description 支付宝支付
             */
            recharge(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if (this.activePayMethod == 1) {
                            rechargeAlipayPC({
                                money: this.payForm.money,
                            }).then((res) => {
                                clearInterval(this.timer);
                                this.alipayModal = true;
                                this.html = res.payUrl;
                                // this.timer = setInterval(() => {
                                //     this.fun(this.timer, res, 'alipay');
                                // }, 2000)
                                window.open(this.html)
                                this.timer = setInterval(() => {
                                    setTimeout(this.paySuc(res), 0)
                                }, 2000);
                            });
                        }
                        if (this.activePayMethod == 2) {
                            wechatpayPC({
                                money: this.payForm.money,
                            }).then((res) => {
                                clearInterval(this.timer);
                                this.wechatpayPCImg = res.code_url;
                                var canvas = document.getElementById("canvas");
                                QRCode.toCanvas(canvas, this.wechatpayPCImg);
                                this.wechatpayModal = true;
                                this.timer = setInterval(() => {
                                    setTimeout(this.paySuc(res), 0)
                                }, 2000);
                            });
                        }
                    }
                });
            },
            paySuc(data) {
                resultsQuery({
                    ordernum: data.ordernum,
                    time: data.time,
                    sign: data.sign
                }).then(res => {
                    const that = this;
                    if(res) {
                        this.$Notice.success({
                            title: '充值成功',
                            duration: 0
                        });
                        clearInterval(that.timer);
                        memberInfo().then(res => {
                            that.balance = res.balance;
                            cookies.set('info', res);
                        })
                        this.alipayModal = false;
                        this.wechatpayModal = false;
                        that.timer = null;
                    }
                })
            },
            // fun(timer, data, payWay) {
            //     setTimeout(() => {
            //         resultsQuery({
            //             ordernum: data.ordernum,
            //             time: data.time,
            //             sign: data.sign
            //         }).then(res => {
            //             if(res) {
            //                 clearInterval(timer);
            //                 this.timer = null;
            //                 setInfo();
            //             }
            //         }).catch(() => {
            //             clearInterval(timer);
            //         })
            //     })
            // },
            visibleChange(boolean) {
                if(!boolean) {
                    clearInterval(this.timer);
                }
            },
            uploadSuc(res) {
                this.formValidate.remittanceVoucher = res.data.path;
            },
            /**
             * @description 提交汇款凭证
             */
            handleSubmit() {
                this.$refs["formValidate"].validate((valid) => {
                    if (valid) {
                        financialRemittanceVoucher(this.formValidate).then(() => {
                            this.modal = false;
                        })
                    }
                });
            },
            getInfo() {
                memberInfo().then(res => {
                    this.balance = res.balance
                })
            }
        },
        created() {
            this.getInfo();
            this.action = `${process.env.VUE_APP_BASE_API}/qhApi/imageUpload`;
            const token = cookies.get("token");
            this.headers = {
                Authorization: "Bearer " + (token ? token : "")
            };
            this.tabValue = this.$route.query.val
        },
    };
</script>

<style lang="less" scoped>
.page-gird-container {
  box-shadow: rgba(10, 32, 51, 0.12) 0px 1px 3px 0px;
  padding: 24px;
  background-color: #fff;
  .bg-color-body-gray {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #f3f4f5;
    padding: 16px;
    margin-bottom: 24px;
    .color-lighten-dark-gray {
      color: #666;
    }
    .color-dark-black {
      color: #282828;
      font-size: 22px;
      margin: 0 8px 0 10px;
    }
  }
}
.r-pay {
  display: flex;
  align-items: center;
  .r-pay-list {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    width: 134px;
    height: 42px;
    margin-bottom: 16px;
    cursor: pointer;
    list-style: none;
    margin-right: 20px;
    border: 1px solid #08f;
    .icon-alipay {
      display: inline-block;
      background-image: url();
      background-position: 0 -32px;
      width: 82px;
      height: 28px;
    }
    .icon-alipay1 {
      display: inline-block;
      background-image: url();
      background-position: 0 -2px;
      width: 105px;
      height: 28px;
    }
    .payment-select {
      display: block;
      position: absolute;
      width: 10px;
      height: 10px;
      bottom: 0;
      right: 0;
      background: url()
        no-repeat 0 0;
    }
  }
}
.icon-alipay {
  background-image: url();
  background-position: 0 -32px;
  width: 82px;
  height: 28px;
  margin-right: 20px;
}
.time {
  margin-bottom: 20px;
}
iframe {
  width: 100%;
  height: 100%;
}
</style>
